﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Tracker.Data.DataContext;
using Tracker.Domain.Entities;

namespace Tracker.Data.Repository
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly IDataContext _context;
        private readonly IDbSet<T> _set;

        public Repository(IDataContext context)
        {
            _context = context;
            _set = _context.CreateDbSet<T>();
        }

        public void Add(T entity)
        {
            _set.Add(entity);
        }

        public void Delete(int id)
        {
            var entity = _set.SingleOrDefault(x => x.ID == id);

            if (entity != null)
            {
                Delete(entity);
            }
        }

        public void Delete(T entity)
        {
            _set.Remove(entity);
        }

        public T Get(Expression<Func<T, bool>> predicate)
        {
            return _set.SingleOrDefault(predicate);
        }

        public IList<T> GetAll()
        {
            return _set.ToList();
        }

        public IList<T> GetAll(Expression<Func<T, bool>> predicate)
        {
            return _set.Where(predicate).ToList();
        }
    }
}
